package com.haha.qqchannelbot.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.haha.qqchannelbot.core.entity.ContentBuilder;
import com.haha.qqchannelbot.core.entity.FileData;
import com.haha.qqchannelbot.core.entity.KeyboardMsg;
import com.haha.qqchannelbot.core.entity.MarkdownMsg;
import com.haha.qqchannelbot.core.entity.ReplyMessage;
import com.haha.qqchannelbot.core.entity.dateCollect.GuildMessageDate;
import com.haha.qqchannelbot.entity.BotMessage;
import com.haha.qqchannelbot.service.BotHttpClient;
import com.haha.qqchannelbot.service.BotRestTemplate;
import com.haha.qqchannelbot.service.FortuneService;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

@Log4j2
@Component
public class MessageEventListener {

    @Resource
    private FortuneService fortuneService;

    @Resource
    private BotHttpClient botHttpClient;

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private BotRestTemplate botRestTemplate;


    @Async
    @EventListener(BotMessage.class)
    public void handlerResult(BotMessage botMessage) {

        GuildMessageDate d = botMessage.getMessageDate();
        String msgId = d.getId();
        String channelId = d.getChannelId();

        String botCode = "<@!"+ botMessage.getBot().getBotId() + ">\u00a0";
        String botCode2 = "<@!"+ botMessage.getBot().getBotId() + "> ";

        String content = d.getContent();
        // 判断是否有@机器人
        if (!content.contains(botCode) && !content.contains(botCode2)) {
            return;
        }

        Boolean markdown = false;

        String replyContent = "请问有什么可以帮助你？";

        if (content.indexOf(" /") > 0) {
            content = content.substring(content.indexOf(" /") + 2).trim();
        }

        if (content.equals("测测情商")) {
            replyContent = EQNumber(d.getAuthor().getId());
        } else if (content.startsWith("生肖运势")) {
            replyContent = fortuneService.animalFortune(content.substring(4).trim());
        } else if (content.startsWith("姓名打分")) {
            String name = content.substring(4).trim();
            replyContent = fortuneService.nameFortune(name);
        } else if (content.startsWith("猜拳")) {
            replyContent = fingerGuessingGame(content);
        }
//        else if (content.startsWith("markdown")) {
//            markdown = true;
//        }

        log.info("messageId ::::::{}", msgId);
        ReplyMessage replyMessage = new ReplyMessage();
        replyMessage.setMsgId(msgId);

        // 拼接回复内容
        ContentBuilder contentBuilder = new ContentBuilder();
        contentBuilder.setContent(replyContent);
        contentBuilder.setAt(d.getAuthor().getId());

        if (content.startsWith("sign")) {
            FileData fileData = new FileData();
            try {
                fileData.setFileInputStream(new FileInputStream("1.jpeg"));
            } catch (FileNotFoundException e) {
                log.info(e.getMessage(), e);
            }
            fileData.setFileName("1.jpeg");
            replyMessage.setFileImage(fileData);

        }

        if (markdown) {

        } else {
            replyMessage.setContent(contentBuilder.getContentBuild());
        }

        try {

            if (replyMessage.getFileImage() != null) {
                HttpResponse<String> stringHttpResponse =
                        botHttpClient.sendPostFormData(String.format("/channels/%s/messages", channelId), replyMessage);
                String body = stringHttpResponse.body();
                log.info("s :::::: {}", body);
                return;
            }

            String body = objectMapper.writeValueAsString(replyMessage);
//            String s = botRestTemplate.postForBodyJson(String.format("/channels/%s/messages", channelId), body);
            HttpResponse<String> stringHttpResponse =
                    botHttpClient.sendPostJson(String.format("/channels/%s/messages", channelId), body);
            String s = stringHttpResponse.body();
            log.info("s :::::: {}", s);

        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public String EQNumber(String qqNumber) {
//        Integer length = EQNumberConfigure.eqNumberMap.get(qqNumber);

        Integer length = null;

        if (length == null) {
            Random random = new Random();
            length = random.nextInt(-10, 300);
        }
//        EQNumberConfigure.eqNumberMap.put(qqNumber, length);

        String s = "今日的情商：" + length + "";

        if (length < 0) {
            s = s + ", 狗不想理你";
        }

        return s+ "\n，随机数生成，不喜勿喷😏";
    }


    /**
     * 猜拳游戏
     * @param content
     * @return
     */
    private String fingerGuessingGame(String content) {

        if (content.equals("猜拳")) {
            return "猜拳游戏：\n" +
                    "猜拳 石头\n" +
                    "猜拳 剪刀\n" +
                    "猜拳 布\n";
        }

        Random random = new Random();
        int i = random.nextInt(3);
        String hand = "";
        if (i == 0) {
            hand = "石头";
        } else if (i == 1) {
            hand = "剪刀";
        } else if (i == 2) {
            hand = "布";
        }


        String[] s = content.split(" ");
        if (s.length != 2) {
            return "参数不合规";
        }
        String s1 = s[1];
        if (!s1.equals("石头") && !s1.equals("剪刀") && !s1.equals("布")) {
            return "参数不合规";
        }
        String result = "我出的是【" + hand + "】，";
        if (s1.equals(hand)) {
            return result + "平局";
        }
        if (s1.equals("石头") && hand.equals("剪刀")) {
            return result + "你赢了";
        }
        if (s1.equals("剪刀") && hand.equals("布")) {
            return result +  "你赢了";
        }
        if (s1.equals("布") && hand.equals("石头")) {
            return result + "你赢了";
        }
        return result + "你输了";

    }

}
